package com.js.sys.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Process;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.google.android.material.textfield.TextInputEditText;
import com.google.gson.Gson;
import com.js.lib_common.base.MvpActivity;
import com.js.lib_common.constant.AppConstant;
import com.js.lib_common.mvp.model.response.LoginResponse;
import com.js.lib_common.mvp.presenter.LoginPresenter;
import com.js.lib_common.mvp.view.LoginView;
import com.js.lib_common.utils.SPUtils;
import com.js.sys.BaseApplication;
import com.js.sys.R;

import butterknife.BindView;
import butterknife.OnClick;


public class LoginActivity extends MvpActivity<LoginPresenter> implements LoginView {


    @BindView(R.id.ll_view)
    LinearLayout llView;
    @BindView(R.id.edt_count)
    TextInputEditText edtCount;
    @BindView(R.id.edt_pwd)
    TextInputEditText edtPwd;
    @BindView(R.id.tv_ip)
    TextView tvIp;
    @BindView(R.id.cb_pwd)
    CheckBox cbPwd;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    private String[] type = {"内网测试环境", "正式环境",};

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tvVersion.setText(getVersionName(this));
        llView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                llView.setFocusable(true);
                llView.setFocusableInTouchMode(true);
                llView.requestFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(llView.getWindowToken(), 0);
                return false;
            }
        });
        tvIp.setText(type[AppConstant.urlType]);
        edtCount.setText(String.format("%s", SPUtils.get(this, "account", "")));

        boolean isCheck = (boolean) SPUtils.get(LoginActivity.this, "cgPwd", false);
        cbPwd.setChecked(isCheck);
        if (isCheck)
            edtPwd.setText(String.format("%s", SPUtils.get(this, "pwd", "")));


    }


    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }


    @Override
    public void loginSuccess(LoginResponse response) {
//        ACache acache = ACache.get(this);
//        acache.put("LoginResponse", response);
        SPUtils.put(this,"LoginResponse", new Gson().toJson(response));
        BaseApplication.userId=response.getUserVo().getId();
        BaseApplication.userName=response.getUserVo().getName();
        toMain();
    }

    @Override
    public void loginFail(String msg) {
        Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
    }


    private void toMain() {
        SPUtils.put(this, "account", edtCount.getText().toString());
        SPUtils.put(this, "pwd", edtPwd.getText().toString());
        SPUtils.put(this, "isLogin", true);
        SPUtils.put(LoginActivity.this, "cgPwd", cbPwd.isChecked());
        Intent it = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(it);

    }


    @Override
    public void onFailed(String message) {
        toastShow(message);
    }




    @OnClick({R.id.btn_login, R.id.tv_ip})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                String name = edtCount.getText().toString();
                String pwd = edtPwd.getText().toString();

                if (!name.isEmpty() && !pwd.isEmpty()) {
                    mvpPresenter.login(name, pwd);
                } else {
                    toastShow("请输入账号密码");
                }
                break;
            case R.id.tv_ip:
                showChooseDialog(tvIp, "ip地址选择");
                break;
        }
    }


//

    private void showChooseDialog(final TextView tv, String title) {
        new AlertDialog.Builder(this).setTitle(title).setItems(type, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int pos) {
                if (pos == 2) {
                    toastShow("当前环境不可用");
                    return;
                }
                tv.setText(String.format("%s", type[pos]));
                dialogInterface.dismiss();
                SPUtils.put(LoginActivity.this, "urlType", pos);
                AppConstant.urlType = pos;
                toastShow("切换成功，3S后将重新启动");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        LoginActivity.this.startActivity(intent);
                        Process.killProcess(Process.myPid());


                    }
                }).start();
            }
        }).show();
    }


    //版本名
    public String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }


    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }
}
